package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    OrderMapper orderMapper;
    /**
     * 处理15分钟未支付的超时订单
     */
    @Scheduled(cron = "0 * * * * ? ")
    //@Scheduled(cron = "0/5 * * * * ? ")
    public void processTimeOutOrder() {
        log.info("处理15分钟未支付的超时订单");
        LocalDateTime orderTime = LocalDateTime.now().plusMinutes(-15);
        //当前时间-15min && 订单处于待付款账单
        List<Orders> list = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, orderTime);
        if(list != null && list.size() > 0) {
            for (Orders orders : list) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason("订单超时，自动取消");
                orderMapper.update(orders);
            }
        }
    }
    /**
     * 处理一直处于派送中订单
     */
    @Scheduled(cron = "0 0 1 * * ? ")//每天凌晨1点处理
    //@Scheduled(cron = "0/5 * * * * ? ")
    public void processDeliveryOrder(){
        log.info("处理一直处于派送中订单");
        LocalDateTime orderTime = LocalDateTime.now().plusMinutes(-15);
        //当前时间-60min && 订单处于派送中账单
        List<Orders> list = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, orderTime);
        if(list != null && list.size() > 0){
            for (Orders orders : list) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
    }
}
